package com.hjl.mybatis.servlet; /**
 * @author ServivE
 * @className ${NAME}
 * @description ${description}
 * @version 0.1
 * @date 2024/8/1 14:46
 * @since jdk11
 */

import com.hjl.mybatis.entity.Emp;
import com.hjl.mybatis.mapper.EmpMapper;
import com.hjl.mybatis.utils.JsonUtil;
import com.hjl.mybatis.utils.PageUtil;
import com.hjl.mybatis.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.javassist.compiler.ast.Variable;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "PageServlet", value = "/page")
public class PageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String ename = request.getParameter("ename");

        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageSize * (pageNum - 1));
        params.put("pageSize", pageSize);
        params.put("ename", ename);

        SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> list = mapper.getEmpByPage(params);
        //emp的总有多少条数据
        int empCount = mapper.getEmpCount();
        //总页数
        int totalPages = PageUtil.getTotalPages(empCount, pageSize);

        Map<String, Object> maps = new HashMap<>();
        maps.put("empList", list);
        maps.put("pageNum", pageNum);
        maps.put("pageSize", pageSize);
        maps.put("totalPages", totalPages);

        JsonUtil.getJson(request, response, maps);
    }
}
